/*
 *  Heap Sort
 */
package algs4.sort;

import java.util.Random;

public class Heap
{
    public static void sort(Comparable[] a) {
        int n = a.length - 1;
        for (int k = n / 2; k > 0; k--)
            sink(a, k, n);

        // version using swim
        /*for (int k = 2; k <= n; k++)
            swim(a, k)*/

        while (n > 1) {
            exch(a, 1, n--);
            sink(a, 1, n);
        }

        // insert the first element to ordered array
        n = a.length - 1;
        int i;
        Comparable v = a[0];
        for (i = 0; i < n && v.compareTo(a[i+1]) > 0; i++)
            a[i] = a[i+1];
        a[i] = v;
    }

    /*private static void swim(Comparable[] a, int k) {
        Comparable v = a[k];

        while (k > 1 && v.compareTo(a[k/2]) > 0) {
            a[k] = a[k/2];
            k /= 2;
        }
        a[k] = v;
    }*/

    private static void sink(Comparable[] a, int k, int n) {
        int i;
        Comparable v = a[k];

        while ((i = 2 * k) <= n) {
            if (i < n && a[i].compareTo(a[i+1]) < 0) i++;
            if (v.compareTo(a[i]) >= 0)     break;
            a[k] = a[i];
            k = i;
        }
        a[k] = v;
    }

    private static void exch(Comparable[] a, int i, int j) {
        Comparable tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }

    private static void show(Comparable[] a) {
        for (Comparable i : a)
            System.out.print(i + " ");
        System.out.println();
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: Command N");
            System.exit(1);
        }
        int n = Integer.parseInt(args[0]);;

        // Build random array of integer
        Integer[] a   = new Integer[n];
        Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < n; i++)
            a[i] = random.nextInt(n);

        System.out.print("BF: "); show(a);
        sort(a);
        System.out.print("AF: "); show(a);
    }
}
